﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;

public class AIOutput
{
    private Dictionary<Type, IDictionary> m_AxisDict = new Dictionary<Type, IDictionary>();
    private Dictionary<Type, IDictionary> m_StreamDict = new Dictionary<Type, IDictionary>();


    /// <summary>
    /// 注册AI输出轴
    /// </summary>
    /// <param name="source">轴的输入源，决定轴的更新时机</param>
    public void RegisterAxis<T>(string axisName, IObservable<Unit> source, Func<T, bool> condition = null) where T : struct
    {
        var type = typeof(T);
        if (!m_StreamDict.TryGetValue(type, out var streamIDict))
        {
            streamIDict = new Dictionary<string, IObservable<T>>();
            m_StreamDict.Add(type, streamIDict);
        }
        var streamDict = streamIDict as Dictionary<string, IObservable<T>>;
        if (streamDict.ContainsKey(axisName))
        {
            Debug.LogError($"AI轴注册失败：轴 {axisName} 已注册，请勿重复注册");
            return;
        }
        var stream = source.Select(_ => GetAxis<T>(axisName));
        if (condition != null)
            stream = stream.Where(condition);
        streamDict.Add(axisName, stream);
    }

    /// <summary>
    /// 获取输出轴
    /// </summary>
    public IObservable<T> GetStream<T>(string axisName) where T : struct
    {
        if (!m_StreamDict.TryGetValue(typeof(T), out var streamIDict))
        {
            Debug.LogError($"AI输出流获取失败：轴 {axisName} 未注册");
            return default;
        }
        var streamDict = streamIDict as Dictionary<string, IObservable<T>>;
        if (!streamDict.TryGetValue(axisName, out var stream))
        {
            Debug.LogError($"AI输出流获取失败：轴 {axisName} 未注册");
        }
        return stream;
    }

    /// <summary>
    /// 获取轴的当前值
    /// </summary>
    public T GetAxis<T>(string axisName) where T : struct
    {
        if (!m_AxisDict.TryGetValue(typeof(T), out var axisIDict))
            return default;
        var axisDict = axisIDict as Dictionary<string, T>;
        axisDict.TryGetValue(axisName, out var paramValue);
        return paramValue;
    }

    /// <summary>
    /// 设置轴的值
    /// </summary>
    public void SetAxis<T>(string axisName, T axisValue) where T : struct
    {
        var type = typeof(T);
        if (!m_AxisDict.TryGetValue(type, out var idict))
        {
            idict = new Dictionary<string, T>();
            m_AxisDict.Add(type, idict);
        }
        var dict = idict as Dictionary<string, T>;
        dict[axisName] = axisValue;
    }

    public void Reset()
    {
        foreach (var kvp in m_AxisDict)
        {
            kvp.Value.Clear();
        }
    }
}